﻿using Aspose.Cells;
using BarcodeDelay.bean;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class LoadBasicHelper
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListDepBarcodes = new ArrayList();
        public Hashtable m_ht_sh_effi = new Hashtable();

        public Hashtable m_ht_main_effi = new Hashtable();


        public Hashtable m_ht_main_line = new Hashtable();

        public bool isEffiCheck = false;

        public event Action AddMessage;
        public event Action QueryDataBasicRes;
        private static LoadBasicHelper instance;
        public static LoadBasicHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new LoadBasicHelper();
                }
                return instance;
            }
        }
        private Thread fThreadLoad = null;
        public void BeginLoadThread()
        {
            try
            {
                initLog();
                m_arListDepBarcodes.Clear();
                if (fThreadLoad != null && (fThreadLoad.ThreadState == ThreadState.Running || fThreadLoad.ThreadState == ThreadState.Background))
                {
                    fThreadLoad.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadLoad != null && (fThreadLoad.ThreadState == ThreadState.Running || fThreadLoad.ThreadState == ThreadState.Background))
                {
                    while (fThreadLoad.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }
                fThreadLoad = new Thread(new ThreadStart(loadBasicData));//出港分析 开辟一个新的线程
                fThreadLoad.IsBackground = true;
                fThreadLoad.Start();

            }
            catch (Exception ex)
            {

            }
        }

        

        public ArrayList loadExcelSHData(Worksheet sheet1,int rowCount)
        {
            ArrayList arListRes = new ArrayList();
            for (int i = 1; i < rowCount; i++)
            {

                Row row = sheet1.Cells.Rows[i];
                if (row.IsBlank)
                {
                    continue;
                }

                string fromSite = row[5].Value.ToString();
                if(fromSite=="")
                {
                    continue;
                }

                string toSite = row[11].Value.ToString();
                if (toSite == "")
                {
                    continue;
                }

                string latestArrival = row[6].Value.ToString();
                if (latestArrival == "")
                {
                    continue;
                }


                string depTime = row[9].Value.ToString();
                if (depTime == "")
                {
                    continue;
                }

                string arrivalSiteTime = row[12].Value.ToString();
                if (arrivalSiteTime == "")
                {
                    continue;
                }

                string spanDays = row[16].Value.ToString();


                string duringTime = "";
               
                if(row[13].Value==null)
                {
                    duringTime = "0";
                }
                else
                {
                    duringTime = row[13].Value.ToString();
                }
          
               

                string validDate = row[27].Value.ToString();
                string curLine = fromSite.ToString() + "$" + toSite.ToString() + "$" + latestArrival.ToString() + "$" +
               depTime.ToString() + "$" + arrivalSiteTime.ToString() + "$" + spanDays.ToString() + "$" + duringTime.ToString() + "$" + validDate.ToString();

                arListRes.Add(curLine);
                

            }
            if (arListRes.Count > 10000)
            {
                addPathData(StoParams.Instance.SJPath, arListRes);
                bool isContainEffiDate = false;
                m_ht_sh_effi = UtilityHelp.Instance.getSHEffi(arListRes, out isContainEffiDate);
            }
            return arListRes;

        }


        public ArrayList loadExcelMainLineData(Worksheet sheet1, int rowCount)
        {
            ArrayList arListRes = new ArrayList();
            for (int i = 1; i < rowCount; i++)
            {

                Row row = sheet1.Cells.Rows[i];
                if (row.IsBlank)
                {
                    continue;
                }

                string fromSiteCode = row[6].Value.ToString();
                if (fromSiteCode == "")
                {
                    continue;
                }

                string toSiteCode = row[8].Value.ToString();
                if (toSiteCode == "")
                {
                    continue;
                }

                string fromSiteName = row[5].Value.ToString();
                if (fromSiteName == "")
                {
                    continue;
                }


                string destSiteName = row[7].Value.ToString();
                if (destSiteName == "")
                {
                    continue;
                }




               

                object objLine= row[9].Value;
                string lineName = "";
                if (objLine!=null)
                {
                    lineName= objLine.ToString();

                }
                if(lineName.Contains("郑州-漯河B12250(6班)"))
                {
                    int a = 0;
                }

                string depTime = row[10].Value.ToString();
                if (depTime == "")
                {
                    continue;
                }



                string arrivalSiteTime = row[12].Value.ToString();
                if (arrivalSiteTime == "")
                {
                    continue;
                }

                string spanDays = row[11].Value.ToString();



                string latestSHZXTime= ""; 
                if (row[13].Value!=null)
                {
                    latestSHZXTime = row[13].Value.ToString();
                }

                string duringTime = "";

                if (row[18].Value == null)
                {
                    duringTime = "0";
                }
                else
                {
                    duringTime = row[18].Value.ToString();
                }
                
                if(duringTime.Contains(":"))
                {
                    string[] arr = duringTime.Split(':');
                    duringTime = ((Convert.ToInt32(arr[0]) * 60) + Convert.ToInt32(arr[1])).ToString();
                }


                string jfyt = "";

                if (row[28].Value == null)
                {
                    jfyt = "";
                }
                else
                {
                    jfyt = row[28].Value.ToString();
                }



               string validDate = row[34].Value.ToString();
                string curLine = fromSiteCode.ToString() + "$" + toSiteCode.ToString() + "$" + fromSiteName.ToString() + "@" + destSiteName.ToString()+"$"+
                    fromSiteCode.ToString() + "@" + toSiteCode.ToString() + "$"+ depTime+"$"+
                 arrivalSiteTime.ToString() + "$" + spanDays.ToString() + "$" + duringTime.ToString() + "$"+ latestSHZXTime.ToString() + "$" + validDate.ToString()
                 +"$"+ lineName+"$"+ jfyt;

                if(curLine.Contains("保定")&& curLine.Contains("西安"))
                {
                    int ee = 0;
                }



                arListRes.Add(curLine);


            }
            if (arListRes.Count > 1000)
            {
                addPathData(StoParams.Instance.MainLinePath, arListRes);
                bool isContainEffiDate = false;
                //m_ht_sh_effi = UtilityHelp.Instance.getSHEffi(arrSHLines,out isContainEffiDate);
                m_ht_main_effi = UtilityHelp.Instance.getMainLineEffi(arListRes,m_ht_main_line);

           
            }
            return arListRes;

        }


        private void loadBasicData()
        {
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListBarcodes = new ArrayList();
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                bool isNewStart = false;
                string barcode = "";
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                DelayAnaHelperGen.Instance.m_arlist_Delayed_BarCodes.Clear();
                int totalRequest = 0;

                //string strUrl = "https://jmsgw.jtexpress.com.cn/transportation/tmsBranchTimeEffectiveInformationNew/page?current=0&size=100&isEnable=1&lineType=2";
                /*string strUrl = "https://jmsgw.jtexpress.com.cn/transportation/tmsBranchTimeEffectiveInformationNew/page?current=1&size=100&isEnable=1&lineType=2";
                JObject jObj = new JObject();
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string res = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "goodsDisperseNew|transportPlatformIndex");
  
                int sjPages = 0;
                int totalRequest = 0;
                if (res.Contains("请求成功"))
                {
                    if (res.Contains("data"))
                    {
                        JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                        JObject obgData = (JObject)jsonObjRes["data"];
                        JToken totalPages = (JToken)obgData["pages"];
                        sjPages = Convert.ToInt32(totalPages.ToString());
                        totalRequest = totalRequest + sjPages;
                    }
              
                    //QueryMessageRes.Invoke();
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("请重新登录jms，并设置机器人在线");
                    return;
                }*/
                JObject jObj = new JObject();
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string strUrl = "https://jmsgw.jtexpress.com.cn/transportation/tmsVehicleLine/page?current=1&size=100&timeType=1&startDate=&endDate=&startProviderId=&endProviderId=&startAttributionArea=&startManagerCode=&endAttributionArea=&endManagerCode=&startManageCodeFlag=&endManageCodeFlag=&isEnables=1%2C3";
                jObj = new JObject();
                postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string res = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "lineMainNew|transportPlatformIndex");
                int lineMainPages = 0;
                if (res.Contains("请求成功"))
                {
                    if (res.Contains("data"))
                    {
                        JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                        JObject obgData = (JObject)jsonObjRes["data"];
                        JToken totalPages = (JToken)obgData["pages"];
                        lineMainPages = Convert.ToInt32(totalPages.ToString());
    
                    }
                    //QueryMessageRes.Invoke();
                }
               // System.Threading.Thread.Sleep(3000);
                StoParams.Instance.totalPages = lineMainPages;
                /*ArrayList arrSHLines = new ArrayList();
                for (int i=1;i<= sjPages; i++)
                {                   
              
                    strUrl = "https://jmsgw.jtexpress.com.cn/transportation/tmsBranchTimeEffectiveInformationNew/page?size=100&isEnable=1&lineType=2&current="+i.ToString();
                    jObj = new JObject();
                    postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                    res = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "goodsDisperseNew|transportPlatformIndex");
                    StoParams.Instance.curPage = StoParams.Instance.curPage + 1;
                    if (res.Contains("data"))
                    {
                        JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                        JObject obgData = (JObject)jsonObjRes["data"];
                        JToken totalPages = (JToken)obgData["pages"];
                        JArray records =(JArray)obgData["records"];
                        foreach(JObject record in records)
                        {
                            string rec = UtilityHelp.Instance.getEffi(record);
                     
                            arrSHLines.Add(rec);
                        }
                        totalRequest = totalRequest + lineMainPages;
                        if(i%10==0)
                        {
                            System.Threading.Thread.Sleep(41000);
                        }
                    }
                    QueryDataBasicRes.Invoke();
                    System.Threading.Thread.Sleep(3000);
                }

                 addPathData(StoParams.Instance.SJPath, arrSHLines);*/

                ArrayList arrMainLines = new ArrayList();
                for (int i = 1; i <= lineMainPages; i++)
                {
                    //临时
                    /*if (i == 2)
                    {
                        break;
                    }*/
                    strUrl = "https://jmsgw.jtexpress.com.cn/transportation/tmsVehicleLine/page?size=100&timeType=1&startDate=&endDate=&startProviderId=&endProviderId=&startAttributionArea=&startManagerCode=&endAttributionArea=&endManagerCode=&startManageCodeFlag=&endManageCodeFlag=&isEnables=1%2C3&current=" + i.ToString();
                    jObj = new JObject();
                    postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                    res = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "lineMainNew|transportPlatformIndex");
                    StoParams.Instance.curPage = StoParams.Instance.curPage + 1;
                    if (res.Contains("data"))
                    {
                        JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                        JObject obgData = (JObject)jsonObjRes["data"];
                        JToken totalPages = (JToken)obgData["pages"];
                        JArray records = (JArray)obgData["records"];
                        foreach (JObject record in records)
                        {
                          
                            string rec = UtilityHelp.Instance.getMainLineEffi(record);
                            arrMainLines.Add(rec);
                        }
                        totalRequest = totalRequest + lineMainPages;
                    }

                    QueryDataBasicRes.Invoke();
                    System.Threading.Thread.Sleep(50);
                }
                addPathData(StoParams.Instance.MainLinePath, arrMainLines);
                bool isContainEffiDate = false;
                //m_ht_sh_effi = UtilityHelp.Instance.getSHEffi(arrSHLines,out isContainEffiDate);
                m_ht_main_effi= UtilityHelp.Instance.getMainLineEffi(arrMainLines, m_ht_main_line);

                /*foreach (ArrayList arListBarcode in m_arListDepBarcodes)
                {
                    intProcess++;

                    foreach (string strBarCode in arListBarcode)
                    {
                        string strLeftTime = "10";

                        
                        JObject jObj = new JObject();                     
                        JArray jarry = new JArray();
                        totalQueryCount = totalQueryCount + 1;
                        jarry.Add(strBarCode);
            
                        string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);

                        //string postData = "{\"isAllPod\":1,\"keywordList\":[\"JT5036358713908\",\"JT5036397106300\"],\"trackingTypeEnum\":\"WAYBILL\",\"countryId\":\"1\"}";
                        string res = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData,"GET", "integratedQuery");
                        //DateTime dtNow = System.DateTime.Now;
                        if(!res.Contains("请求成功"))
                        {
                            if(res.Contains("msg"))
                            {
                                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                                JToken msgToken = jsonObjRes["msg"];
                                StoParams.Instance.resMsg = msgToken.ToString();
                            }
                            else
                            {
                                StoParams.Instance.resMsg = res.ToString();
                            }
                            QueryMessageRes.Invoke();
                            continue;
                        }
                        SiteBean siteBean = UtilityHelp.Instance.getFirstSite(res);
                        if(siteBean.siteCode=="")
                        {
                            continue;
                        }
                        if(MemberInfo.Instance.filter.Contains(siteBean.siteName))
                        {
                            AddMessage.Invoke();
                            continue;
                        }
                        jObj["waybillNo"] = strBarCode.Trim();
                        jObj["receiveNetworkId"] = siteBean.siteId.Trim();
                        jObj["fileUrl"] = "";
                        jObj["receiveNetworkName"] = siteBean.siteName.Trim();
                        jObj["receiveNetworkCode"] = siteBean.siteCode.Trim();
                        jObj["countryId"] = "1";
                        jObj["replyContent"] = MemberInfo.Instance.templete;
                        string postUrl = "https://jmsgw.jtexpress.com.cn/servicequality/leaveMessage/add";
                        postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                        string messge=HttpClient.HttpUtil.Instance.addLeaveMessage(postUrl, postData);
                        if(messge.Contains("成功"))
                        {
                            StoParams.Instance.resMsg = "留言成功";
                        }
                        else
                        {
                            StoParams.Instance.resMsg = "留言失败";
                        }
                        QueryMessageRes.Invoke();
                        Random ran = new Random();

                        
                        int sleepTime = ran.Next(3000, 5000);
                        if(StoParams.Instance.isFastMode)
                        {
                            sleepTime = ran.Next(1000, 2000);
                        }
                        Thread.Sleep(sleepTime);
                        StoParams.Instance.currentBarcode = strBarCode.Trim();
                        TimeSpan tsp = System.DateTime.Now - dtStart;
                        string spent = tsp.ToString(@"hh\:mm\:ss");
                        Program.m_frmain.SetTextMessage(intProcess, m_arListDepBarcodes.Count, spent);
                        AddMessage.Invoke();
                        System.DateTime dtBegin = System.DateTime.Now;

                        if (res.Length > 300)
                        {
                            queryServerResTime++;
                        }
                        else
                        {
                            continue;
                        }
                        lock (Program.obj_left_count)
                        {
                            StoParams.Instance.day_left = StoParams.Instance.day_left - arListBarcode.Count;
                            if (StoParams.Instance.day_left <= 0)
                            {
                                StoParams.Instance.day_left = 0;
                                //break;//暂时去掉
                            }
                        }
                        //continue;//暂时不解析
                        System.DateTime dtEndT = System.DateTime.Now;
                        TimeSpan tsSpend = dtEndT - dtBegin;
                        int oneQuery = Convert.ToInt32(tsSpend.TotalSeconds);
                        sumQueryTime = sumQueryTime + oneQuery;
                        avgQueryTime = Convert.ToInt32(sumQueryTime / intProcess);

             
                    }




                }*/



            }
            catch (Exception ex)
            {

            }
            int tiot = queryServerResTime;
        }

        public ArrayList getDispatchSite(string dispatchSiteName)
        {
            ArrayList arListRes = new ArrayList();
            try
            {
                foreach(DictionaryEntry de in m_ht_sh_effi)
                {
                    Hashtable ht = de.Value as Hashtable;
                    if(ht.ContainsKey(dispatchSiteName))
                    {
                        arListRes = ht[dispatchSiteName] as ArrayList;
                    }
                }
            }
            catch(Exception ex)
            {

            }
            return arListRes;
        }

        private void addPathData(string path,ArrayList arListLines)
        {
            try
            {
                FileStream bFile = new FileStream(path, FileMode.Create);
                StreamWriter swb = new StreamWriter(bFile);
                foreach (string line in arListLines)
                {
                    swb.WriteLine(line);
                }
                swb.Close();
                swb = null;
            }
            catch(Exception ex)
            {

            }
            
        }

        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadLoad != null && (fThreadLoad.ThreadState == ThreadState.Running || fThreadLoad.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadLoad.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
